using Newtonsoft.Json;
using LiJ.Common.Core;
using LiJ.Http.Mos;
using LiJ.Framework.Official.Basic.Mos;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace LiJ.Framework.Official.Basic
{
	/// <summary>
	/// 消息相关接口
	/// </summary>
	public class WxOffMassApi : WxOffBaseApi
	{
		/// <summary>
		///
		/// </summary>
		/// <param name="config">配置信息，如果这里不传，需要在程序入口静态 WxBaseApi.DefaultConfig 属性赋值</param>
		public WxOffMassApi(AppConfig config = null)
			: base(config)
		{
		}

		public async Task<WxBaseResp> SetTemplateIndustry(int industryId1, int industryId2)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/template/api_set_industry",
				CustomBody = string.Format("{{\"industry_id1\":\"{0}\",\"industry_id2\":\"{1}\"}}", industryId1, industryId2)
			};
			return await base.RestCommonOffcialAsync<WxBaseResp>(req, null);
		}

		/// <summary>
		/// 获取设置的行业信息
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetTemplateIndustryResp> GetTemplateIndustry()
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Get,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/template/get_industry"
			};
			return await base.RestCommonOffcialAsync<WxGetTemplateIndustryResp>(req, null);
		}

		/// <summary>
		/// 添加模板
		/// </summary>
		/// <param name="shortTemplateId">模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式</param>
		/// <returns></returns>
		public async Task<WxAddTemplateResp> AddTemplate(string shortTemplateId)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/template/api_add_template",
				CustomBody = string.Format("{{\"template_id_short\":\"{0}\"}}", shortTemplateId)
			};
			return await base.RestCommonOffcialAsync<WxAddTemplateResp>(req, null);
		}

		/// <summary>
		/// 删除模板
		/// </summary>
		/// <param name="templateId">公众帐号下模板消息ID</param>
		/// <returns></returns>
		public async Task<WxAddTemplateResp> DeleteTemplate(string templateId)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/template/del_private_template",
				CustomBody = string.Format("{{\"template_id\":\"{0}\"}}", templateId)
			};
			return await base.RestCommonOffcialAsync<WxAddTemplateResp>(req, null);
		}

		/// <summary>
		/// 获取公众号下模板列表
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetTemplateListResp> GetTemplateList()
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Get,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/template/get_all_private_template"
			};
			return await base.RestCommonOffcialAsync<WxGetTemplateListResp>(req, null);
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="openId">普通用户的标识，对当前公众号唯一</param>
		/// <param name="templateId">模板Id</param>
		/// <param name="url">消息详情链接地址</param>
		/// <param name="data">消息数据， 格式可以为： new{first = new {value = "用户", color = "#173177"},{...}}</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SendTemplateAsync(string openId, string templateId, string url, object data)
		{
			LHttpRequest LHttpRequest = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/template/send"
			};
			var value = new
			{
				touser = openId,
				template_id = templateId,
				url = url,
				data = data
			};
			LHttpRequest.CustomBody = JsonConvert.SerializeObject(value);
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///   上传群发消息中的图文消息素材【订阅号与服务号认证后均可用】
		///   群发接口中的上传素材接口
		/// </summary>
		/// <param name="articles"></param>
		/// <returns></returns>
		public async Task<WxMediaResp> UploadMassMsgArticlesAsync(List<WxArticleInfo> articles)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/media/uploadnews";
			LHttpRequest.CustomBody = JsonConvert.SerializeObject(new
			{
				articles
			});
			return await base.RestCommonOffcialAsync<WxMediaResp>(LHttpRequest, null);
		}

		/// <summary>
		///   上传群发消息中的视频【订阅号与服务号认证后均可用】 
		///   群发接口中的上传视频
		/// </summary>
		/// <param name="mediaId">media_id需通过基础支持中的上传下载多媒体文件来得到</param>
		/// <param name="title">消息的标题</param>
		/// <param name="desp">消息的描述</param>
		/// <returns></returns>
		public async Task<WxMediaResp> UploadMassMsgVedioAsync(string mediaId, string title, string desp)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/media/uploadvideo";
			LHttpRequest.CustomBody = string.Format("{{\"media_id\":\"{0}\",\"title\":\"{1}\",\"description\":\"{2}\"}}", mediaId, title, desp);
			return await base.RestCommonOffcialAsync<WxMediaResp>(LHttpRequest, null);
		}

		/// <summary>
		/// 根据Tag群发消息接口
		/// </summary>
		/// <param name="tagId">群发到的标签的tag_id，参加用户管理中用户分组接口，若is_to_all值为true，可不填写tag_id</param>
		/// <param name="isToAll">用于设定是否向全部用户发送，值为true或false，选择true该消息群发给所有用户，选择false可根据tag_id发送给指定群组的用户</param>
		/// <param name="msgType">群发的消息类型</param>
		/// <param name="data">素材消息的media_id,  text类型时是content, wxcard 时是card_id </param>
		/// <param name="sendIgnoreReprint">当 send_ignore_reprint=1时，文章被判定为转载时，且原创文允许转载时，将继续进行群发操作。当 send_ignore_reprint =0时，文章被判定为转载时，将停止群发操作。send_ignore_reprint 默认为0</param>
		/// <returns></returns>
		public async Task<WxSendMassMsgResp> SendMassMsgByTagAsync(int tagId, bool isToAll, WxMassMsgType msgType, string data, int sendIgnoreReprint = 0)
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"filter\":{");
			stringBuilder.Append("\"is_to_all\":").Append(isToAll).Append(",");
			stringBuilder.Append("\"tag_id\":").Append(tagId);
			stringBuilder.Append("},");
			WxOffMassApi.GenerateMsgBody(msgType, data, stringBuilder);
			stringBuilder.Append("}");
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/mass/sendall";
			LHttpRequest.CustomBody = stringBuilder.ToString();
			return await base.RestCommonOffcialAsync<WxSendMassMsgResp>(LHttpRequest, null);
		}

		private static void GenerateMsgBody(WxMassMsgType msgType, string data, StringBuilder msgStr)
		{
			msgStr.Append("\"").Append(msgType).Append("\":{");
			switch (msgType)
			{
			case WxMassMsgType.text:
				msgStr.Append("\"content\":\"").Append(data).Append("\"");
				break;
			case WxMassMsgType.wxcard:
				msgStr.Append("\"card_id\":\"").Append(data).Append("\"");
				break;
			default:
				msgStr.Append("\"media_id\":\"").Append(data).Append("\"");
				break;
			}
			msgStr.Append("},");
			msgStr.Append("\"msgtype\":\"").Append(msgType);
			if (msgType == WxMassMsgType.mpnews)
			{
				msgStr.Append("\",").Append("\"send_ignore_reprint\":").Append(msgType);
			}
		}

		/// <summary>
		/// 根据Tag群发消息接口
		/// </summary>
		/// <param name="openIds"></param>
		/// <param name="msgType">群发的消息类型</param>
		/// <param name="data">素材消息的media_id,  text类型时是content, wxcard 时是card_id </param>
		/// <param name="sendIgnoreReprint">当 send_ignore_reprint=1时，文章被判定为转载时，且原创文允许转载时，将继续进行群发操作。当 send_ignore_reprint =0时，文章被判定为转载时，将停止群发操作。send_ignore_reprint 默认为0</param>
		/// <returns></returns>
		public async Task<WxSendMassMsgResp> SendMassMsgByOpenIds(List<string> openIds, WxMassMsgType msgType, string data, int sendIgnoreReprint = 0)
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"touser\":[");
			for (int i = 0; i < openIds.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(",");
				}
				stringBuilder.Append("\"").Append(openIds[i]).Append("\"");
			}
			stringBuilder.Append("],");
			WxOffMassApi.GenerateMsgBody(msgType, data, stringBuilder);
			stringBuilder.Append("}");
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/mass/send";
			LHttpRequest.CustomBody = stringBuilder.ToString();
			return await base.RestCommonOffcialAsync<WxSendMassMsgResp>(LHttpRequest, null);
		}

		/// <summary>
		///  删除群发消息
		/// </summary>
		/// <param name="msgId"></param>
		/// <returns></returns>
		public async Task<WxBaseResp> DeleteMassMsgAsync(long msgId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/mass/delete";
			LHttpRequest.CustomBody = string.Format("{{\"msg_id\":{0}}}", msgId);
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///  查询群发消息状态
		/// </summary>
		/// <param name="msgId"></param>
		/// <returns></returns>
		public async Task<WxMassMsgStateResp> GetMassMsgStateAsync(long msgId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/mass/get";
			LHttpRequest.CustomBody = string.Format("{{\"msg_id\":{0}}}", msgId);
			return await base.RestCommonOffcialAsync<WxMassMsgStateResp>(LHttpRequest, null);
		}

		/// <summary>
		/// 根据Tag群发消息接口
		/// </summary>
		/// <param name="openId">openid，wxName和openId同时赋值时，以wxname优先</param>
		/// <param name="wxName">微信名称，wxName和openId同时赋值时，以wxname优先</param>
		/// <param name="msgType">群发的消息类型</param>
		/// <param name="data">素材消息的media_id,  text类型时是content, wxcard 时是card_id </param>
		/// <param name="sendIgnoreReprint">当 send_ignore_reprint=1时，文章被判定为转载时，且原创文允许转载时，将继续进行群发操作。当 send_ignore_reprint =0时，文章被判定为转载时，将停止群发操作。send_ignore_reprint 默认为0</param>
		/// <returns></returns>
		public async Task<WxSendMassMsgResp> PreviewMassMsgAsync(string wxName, string openId, WxMassMsgType msgType, string data, int sendIgnoreReprint = 0)
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			if (!string.IsNullOrEmpty(wxName))
			{
				stringBuilder.Append("\"towxname\":\"").Append(wxName).Append("\",");
			}
			if (!string.IsNullOrEmpty(openId))
			{
				stringBuilder.Append("\"touser\":\"").Append(openId).Append("\",");
			}
			WxOffMassApi.GenerateMsgBody(msgType, data, stringBuilder);
			stringBuilder.Append("}");
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/mass/preview";
			LHttpRequest.CustomBody = stringBuilder.ToString();
			return await base.RestCommonOffcialAsync<WxSendMassMsgResp>(LHttpRequest, null);
		}
	}
}
